﻿//-----------------------------------------------------------------------
// <copyright file="Serializer.cs" company="CodePlex">
//     Copyright (c) Doug Holland, CodePlex. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CodePlex.Diagnostics.Model
{
    using System;

    using System.Globalization;

    using System.IO;
    
    using System.Runtime.Serialization;
    
    using System.Xml;

    /// <summary>
    /// Serializes and deserializes object graphs using the <see cref="T:System.Runtime.Serialization.DataContractSerializer"/> class.
    /// </summary>
    /// <typeparam name="T">The type of object to be serialized or deserialized.</typeparam>
    internal static class Serializer<T>
    {
        #region internal static Serialize(T instance)

        /// <summary>
        /// Serializes the specified object graph.
        /// </summary>
        /// <param name="instance">The object graph to be serialized.</param>
        /// <returns>A <see cref="T:System.String"/> containing the serialized object graph.</returns>
        internal static string Serialize(T instance)
        {
            if (instance == null)
            {
                return null;
            }

            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            using (StringWriter stringWriter = new StringWriter(CultureInfo.CurrentCulture))
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
                {
                    serializer.WriteObject(xmlWriter, instance);
                }

                return stringWriter.ToString();
            }
        }

        #endregion

        #region internal static T Deserialize(string xml)

        /// <summary>
        /// Deserializes the specified serialized object graph.
        /// </summary>
        /// <param name="xml">The object graph to be deserialized.</param>
        /// <returns>The deserialized object graph.</returns>
        internal static T Deserialize(string xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            using (StringReader stringReader = new StringReader(xml))
            {
                using (XmlReader xmlReader = XmlReader.Create(stringReader))
                {
                    return (T)serializer.ReadObject(xmlReader);
                }
            }
        }

        #endregion
    }
}
